package org.tabularium.text.se;

import java.io.IOException;

import org.apache.commons.lang3.NotImplementedException;


/**
 * Iterator over the keys stored in the SqlRawStorer.
 * 
 * @author fabio
 *
 */
public class SqlRawStorerIterator implements DocIterator {
	protected int[] ids;
	
	protected SqlRawStorer storer;

	protected int currentKey = 0;
	
	protected byte[] currentValue = null;

	public SqlRawStorerIterator(SqlRawStorer storer, int[] ids) {
		this.storer = storer;
		this.ids = ids;
	}

	/**
	 * Returns true if the iteration has more keys.
	 */
	public boolean hasNext() {
		return currentKey < ids.length;
	}

	/**
	 * Returns the next key in the iteration.
	 */
	public Object next() {
		String key = null;
		if (currentKey < ids.length) {
			try {
				key = storer.getKeyById(ids[currentKey]);
			} catch (Exception ex) {
				throw new RuntimeException(
						"LinkDb.getUrlById() raised exception: "
								+ ex.toString());
			}
			currentKey++;
		}
		return key;
	}

	/**
	 * Removes from the underlying collection the last key returned by the
	 * iterator.
	 * <p>
	 * Warninig: yet to be implemented.
	 */
	public void remove() {
		throw new NotImplementedException("not yet implemented");
	}

	@Override
	public byte[] getObj() {
		try {
			String key = storer.getKeyById(ids[currentKey]);
			long ts = storer.getTimestampById(ids[currentKey]);
			if (key != null) {				
				return storer.retrieve(key, ts);
			}
		} catch (IOException ex) {			
		}
		return null;
	}

	@Override
	public void interrupt() {
	}
}
